import { View, Text } from "@tarojs/components";
import { Image, Cell, Dialog, Button } from "@nutui/nutui-react-taro";
import { ArrowRight } from "@nutui/icons-react-taro";
import Taro, { navigateTo, usePullDownRefresh, useDidShow } from "@tarojs/taro";
import { useContext, useState, useEffect, useRef } from "react";
import { LoginContext } from "@/context/login-provider";
import { UserContext } from "@/context/user-provider";
import { removeStorage } from "@/utils/storage";
import Exchange from "@/components/exchange";
import { useRouter } from "@tarojs/taro";
import { bindCode, getUserCode } from "@/api/my";
const My = () => {
  const router = useRouter();
  const { params } = router;
  const { member, setMember, getUser } = useContext(UserContext);
  const { userInfo } = useContext(LoginContext);

  // 激活码激活
  const [codeOpen, setCodeOpen] = useState(false);
  const exchangeRecord = () => {
    if (userInfo) {
      setCodeOpen(true);
    } else {
      Dialog.open("login", {
        content: "当前账户未登录，是否立即登录？",
        confirmText: "立即登录",
        cancelText: "暂不登录",
        onConfirm: () => {
          navigateTo({ url: "/pages/login/index" });
          Dialog.close("login");
        },
        onCancel: () => {
          Dialog.close("login");
        },
      });
    }
  };
  usePullDownRefresh(async () => {
    await getUser();
    Taro.stopPullDownRefresh();
  });
  const queryRef = useRef("");
  Taro.useLoad((options) => {
    if (options.hasOwnProperty("q") && options.q) {
      queryRef.current = decodeURIComponent(options.q)?.split("=")[1];
      console.log(queryRef.current, "queryRef.current123");
    }
  });
  useDidShow(async () => {
    if (userInfo) {
      getUserCode();
    } else {
      setMember(null);
    }
    await getUser();
  });
  useEffect(() => {
    if (userInfo && queryRef.current) {
      bindCode({
        memberId: userInfo?.userId,
        adminId: queryRef.current,
      }).then((res) => {
        if (res.data) {
          Taro.showToast({
            title: "网站账号绑定成功",
            icon: "none",
          });
          queryRef.current = "";
        }
      });
    }
  }, [userInfo]);

  return (
    <View className="bg-[#F5F5F5] p-3 h-screen box-border my-page relative">
      <View
        onClick={() => {
          if (userInfo) {
            navigateTo({ url: "/pages/member/index" });
          } else {
            Dialog.open("login", {
              content: "当前账户未登录，是否立即登录？",
              confirmText: "立即登录",
              cancelText: "暂不登录",
              onConfirm: () => {
                navigateTo({ url: "/pages/login/index" });
                Dialog.close("login");
              },
              onCancel: () => {
                Dialog.close("login");
              },
            });
          }
        }}
        className="p-4 bg-white flex justify-between items-center rounded-md"
      >
        <View className="flex items-center gap-2">
          <div className="w-[70px] h-[70px] !p-0 rounded-full overflow-hidden flex justify-center items-center">
            <Image width={80} height={80} src={member?.avatar} />
          </div>
          {userInfo ? (
            <View className=" flex-1 flex flex-col justify-around items-start">
              <View className="font-bold text-[#333]">{member?.nickname}</View>
              {/* <Text className="text-gray-500 text-xs mt-[10px] mb-[5px]">
                手机号：{member?.mobile}
              </Text> */}
              {/* <Text className="text-gray-500 text-xs mt-[10px] mb-[5px]">
                用户昵称：
                <Text
                  className="text-[#673ab7]"
                  onClick={(e) => {
                    e.stopPropagation();
                    Taro.setClipboardData({
                      data: userInfo?.userId?.toString(),
                    });
                  }}
                >
                  {userInfo?.nickname}
                </Text> 
              </Text>*/}
            </View>
          ) : (
            <Text
              className="font-bold text-[#333]"
              onClick={(e) => {
                e.stopPropagation();
                navigateTo({ url: "/pages/login/index" });
              }}
            >
              点击登录
            </Text>
          )}
        </View>
        <img
          className="w-[20px] h-[20px]"
          src={require("../../assets/my/right.svg")}
        />
      </View>
      {member?.adminUserId && (
        <Cell
          onClick={() => navigateTo({ url: "/pages/distribution/index" })}
          title="合伙人分销中心"
          align="center"
          extra={<ArrowRight />}
        />
      )}
      {/* <View
        style={{
          marginTop: !member?.adminUserId ? "10px" : "0",
        }}
        className="bg-white px-[32rpx] py-[26rpx] rounded-md"
      >
        <contact-cell
          plugid="34d0276c85dda0279111a01afb3db40a"
          title={
            <Space align="center">
              <View>丁老师微信：18612345678</View>
              <View
                onClick={() => {
                  Taro.setClipboardData({
                    data: "18612345678",
                  });
                }}
                className="text-[#673ab7]"
              >
                复制
              </View>
            </Space>
          }
          align="center"
        />
      </View> */}

      <Cell
        onClick={exchangeRecord}
        title="输入合集兑换码"
        align="center"
        extra={<ArrowRight />}
      />
      <Cell
        onClick={() => {
          if (userInfo) {
            navigateTo({ url: "/pages/exchangeRecord/index" });
          } else {
            Dialog.open("login", {
              content: "当前账户未登录，是否立即登录？",
              confirmText: "立即登录",
              cancelText: "暂不登录",
              onConfirm: () => {
                navigateTo({ url: "/pages/login/index" });
                Dialog.close("login");
              },
              onCancel: () => {
                Dialog.close("login");
              },
            });
          }
        }}
        title="兑换记录"
        align="center"
        extra={<ArrowRight />}
      />
      {userInfo && (
        <Button
          className="w-[calc(100%-24px)] !absolute bottom-4 left-3"
          type="primary"
          onClick={() => {
            Dialog.open("login", {
              title: "退出登录",
              content: "退出登录暂时无法接受作品集消息推送",
              onConfirm: () => {
                removeStorage("userInfo");
                navigateTo({ url: "/pages/login/index" });
                Dialog.close("login");
              },
              onCancel: () => {
                Dialog.close("login");
              },
            });
          }}
        >
          退出登录
        </Button>
      )}
      <Dialog id="login" />
      <Exchange
        codeOpen={codeOpen}
        setCodeOpen={setCodeOpen}
        onExchange={() => Taro.reLaunch({ url: "/pages/course/index" })}
      />
    </View>
  );
};

export default My;
